package com.rzhd.coursepatriarch.common.api.base;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;

import com.rzhd.coursepatriarch.common.R;
import com.rzhd.coursepatriarch.common.base.BaseApplication;
import com.rzhd.coursepatriarch.common.utils.ToastUtils;
import com.rzhd.coursepatriarch.common.view.dialog.LoadingDialog;

import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * @author yql
 * Time: 2018/6/10.
 */
public abstract class BaseObserver<T> implements Observer<T> {

    private String TAG = getClass().getSimpleName();

    /**
     * 上下文对象
     */
    private Context mContext;

    /**
     * loading动画
     */
    private LoadingDialog mLoadingDialog;

    /**
     * 相当于 RxJava 1.x 中的 Subscription， 用于解除订阅。
     */
    private Disposable mDisposable;

    public BaseObserver() {

    }

    public BaseObserver(Context context) {
        this.mContext = context;
    }

    public BaseObserver(Context context, boolean isShowLoading) {
        this.mContext = context;
        if (isShowLoading) {
            mLoadingDialog = new LoadingDialog();
            mLoadingDialog.show(((AppCompatActivity) mContext).getSupportFragmentManager());
            mLoadingDialog.setDialogCancelListener(new LoadingDialog.OnDialogCancelListener() {
                @Override
                public void onCancel() {
                    unSubscribe();
                    Log.e(TAG, "系统返回键消失loading");
                }
            });
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        Log.d(TAG, "onSubscribe");
        this.mDisposable = d;
    }

    /**
     * 数据返回时回调
     *
     * @param json
     */
    @Override
    public abstract void onNext(T json);

    /**
     * 数据返回失败错误回调
     *
     * @param e
     */
    @Override
    public void onError(Throwable e) {
        unSubscribe();
        Log.e(TAG, "onError:" + e);
        e.printStackTrace();
        if (e instanceof SocketTimeoutException || e instanceof TimeoutException) {
            ToastUtils.shortToast(BaseApplication.getInstance().getResources().getString(R.string.http_error_time_out));
        } else if (e instanceof ConnectException) {
            ToastUtils.shortToast(BaseApplication.getInstance().getResources().getString(R.string.http_error_connect));
        } else if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            switch (httpException.code()) {

                case HttpURLConnection.HTTP_UNAUTHORIZED:
                case HttpURLConnection.HTTP_FORBIDDEN:
                case HttpURLConnection.HTTP_NOT_FOUND:
                case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
                case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
                case HttpURLConnection.HTTP_SERVER_ERROR:
                case HttpURLConnection.HTTP_BAD_GATEWAY:
                case HttpURLConnection.HTTP_UNAVAILABLE:
                default:
                    ToastUtils.shortToast(BaseApplication.getInstance().getResources().getString(R.string.http_error_service));
                    break;
            }
        } else {
            if (!TextUtils.isEmpty(e.getMessage())) {
                ToastUtils.shortToast("请检查网络是否有效");
            }
        }
    }

    @Override
    public void onComplete() {
        unSubscribe();
    }

    public void unSubscribe() {
        /*
                    在RxJava 2.x 中，新增的Disposable可以做到切断的操作，让Observer观察者不再接收上游事件
                    isDisposable = true  已经处于切断状态
                     */
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        dismissDialog();
    }


    private void dismissDialog() {
        if (mContext == null) {
            return;
        }
        if (mLoadingDialog != null && mLoadingDialog.getShowsDialog()) {
            mLoadingDialog.dismissAllowingStateLoss();
        }
    }
}
